<template>
    <div :class='{[$style.hidden] : pageType == 2}'>
        <div :class='$style.industry'>
            <span :class='$style.title'>选择行业：</span>
            <div>
                <a-cascader style='width:300px' placeholder='全部行业' change-on-select v-model:value='industry' :options='industryOptions' :load-data='loadIndustry'></a-cascader>
            </div>
            <span class='m-l-30' :class='$style.title'>选择股票：</span>
            <div>
                <XStockSelect style='width:300px' placeholder='输入股票' type='1' @change='selectStock' allowClear />
            </div>
        </div>
        <div class='m-t-20' :class='$style.zhibiao'>
            <span :class='$style.title'>选股指标：</span>
            <div class='flex-1'>
                <a-descriptions :class='$style.zhibiaoTable' bordered layout='vertical'>
                    <a-descriptions-item label='所有指标'>
                        <div style="min-width:200px">
                            <a-tabs>
                                <a-tab-pane v-for='(factor, index) in factorList' :key='index' :tab='factor.label'>
                                    <XOptionCollapse :rows='factor.children' :selectedApi='selectedFactor' />
                                </a-tab-pane>
                            </a-tabs>
                        </div>
                    </a-descriptions-item>
                    <a-descriptions-item label='已选择'>
                        <table :class='$style.table'>
                            <tr>
                                <th>指标</th>
                                <th>比较符</th>
                                <th>值</th>
                            </tr>
                            <template v-for='(item, index) in selectedFactorList' :key='item.id'>
                                <tr>
                                    <td>
                                        <a-tooltip v-if='item.label.length > 15' :title='item.label'>
                                            <a-tag closable @close='removeFactor(index)'>{{item.label.slice(0, 15)}}...</a-tag>
                                        </a-tooltip>
                                        <a-tag v-else closable @close='removeFactor(index)'>{{item.label}}</a-tag>
                                    </td>
                                    <td>
                                        <a-select v-model:value='item.operator' :options='COMPARE_OPERATOR' @change='v => changeOperator(v,index)'></a-select>
                                    </td>
                                    <td>
                                        <div style="white-space:nowrap">
                                            <span class='relative'>
                                                <a-input-number :class='$style.valueInput' v-model:value.number='item.min' @input='v => input(v, index, "min")' />
                                                <span v-if='item.operator == 3' :class='$style.percentSign'>%</span>
                                                <template v-if='item.operator == 2 || item.operator == 3 || item.operator == 4'>
                                                    <span :class='$style.between'>至</span>
                                                    <a-input-number :class='$style.valueInput' v-model:value.number='item.max' @input='v => input(v, index, "max")' />
                                                    <span v-if='item.operator == 3' :class='$style.percentSign'>%</span>
                                                </template>
                                                <div v-if='item.showError' :class='$style.error'>{{item.error}}</div>
                                            </span>
                                        </div>
                                    </td>
                                </tr>
                            </template>
                        </table>
                        <div class='m-t-30 text-center'>
                            <a-button type='primary' :loading='loading' @click='submit'>立即选股</a-button>
                        </div>
                    </a-descriptions-item>
                </a-descriptions>
                

                <div class='m-t-30'>
                    <template v-if='!loading'>
                        <div>
                            <span>
                                共 <span class='color-forbidden bold'>{{dataSource.length}}</span> 只选股结果
                            </span>
                            <span class='m-l-20' v-if='props.type != "select" && dataSource.length > 0'>
                                <a-button type='primary' @click='goBackTest'>去回测</a-button>
                            </span>
                        </div>
                        <div class='m-t-20'>
                            <a-table rowKey='code' :class='$style.resultTable' align='center' :row-selection='rowSelection' :pagination='false' :dataSource='dataSource' :columns='columns'></a-table>
                        </div>
                    </template>
                    <template v-else>
                        <a-skeleton active />
                    </template>
                </div>
            </div>
        </div>
    </div>

    <div v-if='pageType == 2'>
        <BackTest :shares='selectedRows' />
    </div>

</template>

<script lang='ts' setup>
    import { industryApi } from '@/api/industry'
    import { factorApi, stockSelectorApi } from '@/api/stockSelector'
    import { COMPARE_OPERATOR } from '@/constant'
    import { reactive, ref } from '@vue/reactivity'
    import { message } from 'ant-design-vue'
    import BackTest from './BackTest.vue'

    const props = defineProps<{
        type:string
    }>()

    const pageType = ref(1)

    const industryOptions = reactive<any[]>([])
    const factorList = reactive<any[]>([])

    const selfSelectStock = ref(null)

    const industry = ref(null)
    const selectedFactorSet = new Set()
    const selectedFactorList = reactive<any[]>([])
    const loading = ref(false)
    const columns = [{title : '股票名称', dataIndex : 'name'}, {title : '股票代码', dataIndex : 'code'}]
    const dataSource = reactive<any[]>([])
    const selectedRows = ref<any[]>([])


    function selectStock(e) {
        console.log('接收到的', e)
        selfSelectStock.value = e
    }

    async function loadIndustry(selectedOptions) {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        const rows = await industryApi(targetOption.id)
        targetOption.loading = false
        targetOption.children = rows
    }



    const rowSelection = ref({
        onChange(keys, rows) {
            selectedRows.value.splice(0)
            selectedRows.value.push(...rows)
        }
    })

    function goBackTest() {
        if(selectedRows.value.length == 0) {
            message.info('请选择股票')
        }else {
            pageType.value = 2
        }
    }

    industryApi().then(rows => {
        industryOptions.push(...rows)
    })

    factorApi().then(rows => {
        factorList.push(...rows)
    })


    function selectedFactor(e) {
        if(!selectedFactorSet.has(e.id)) {
            selectedFactorSet.add(e.id)

            selectedFactorList.push({
                showError : false,
                error : '',
                label : e.label,
                id : e.id,
                values : [e.table, e.id],
                operator : 0,
                min : 1,
                max : 1
            })

        }
    }
    
    function removeFactor(index:number) {
        const factor = selectedFactorList[index]
        selectedFactorSet.delete(factor.id)
        selectedFactorList.splice(index, 1)
    }

    function changeOperator(operator, index) {
        const item = selectedFactorList[index]
        const rs = input(item.min, index, 'min')
        if(!rs) {
            if(!(operator == 0 || operator == 1)) {
                input(item.max, index, 'max')
            }
        }
        
    }

    function input(value, index, target) {
        const item = selectedFactorList[index]
        try {
            const operator = item.operator
            if(value === '') {
                item.showError = true
                item.error = (operator == 0 || operator == 1) ? '请填写数据' : '请填写两个区间数据'
            }else if(operator == 0 || operator == 1 || operator == 4) { //排名
                value = Number(value)
                if(value < 0) {
                    item.showError = true
                    item.error = '不能小于0'
                }else {
                    if(value != Math.floor(value)) {
                        item.showError = true
                        item.error = '必须为整数'
                    }else {

                        if(operator == 4 && item.min > item.max) {
                            item.showError = true
                            item.error = '最大值不能小于最小值'
                        }else {
                            item.showError = false
                        }
                        
                    }
                }

            }else if(operator == 2) { //值区间
                if(item.min > item.max) {
                    item.showError = true
                    item.error = '最大值不能小于最小值'
                }else {
                    item.showError = false
                }
            }else if(operator == 3) { //百分比
                if(value < 0) {
                    item.showError = true
                    item.error = '不能小于0%'
                }else if(value > 100) {
                    item.showError = true
                    item.error = '不能超过100%'
                }else {
                    if(item.min > item.max) {
                        item.showError = true
                        item.error = '最大值不能小于最小值'
                    }else {
                        item.showError = false
                    }
                }
            }
        } catch (error) {
            
        }

        return item.showError
    }

    async function submit() {
        if(selfSelectStock.value) {
            console.log('有选择股票')
            dataSource.splice(0)
            const key = Object.keys(selfSelectStock.value)
            dataSource.push({code : key[0], name : selfSelectStock.value[key[0]]})
            console.log({code : key[0], name : selfSelectStock.value[key[0]]})
            return
        }


        let code = '028'
        const screening_conditions = []
        let success = true
        for(let i = 0; i < selectedFactorList.length; i ++) {
            const item = selectedFactorList[i]
            const r = input(item.min, i, 'min')
            console.log(r)
            if(r) success = false
            if(!r && !(item.operator == 0 || item.operator == 1)) {
                const r = input(item.max, i, 'max')
                console.log(r)
                if(r) success = false
            }
            
            if(!success) continue

            const value = [...item.values, item.operator]
            if(item.operator == 0 || item.operator == 1) {
                value.push(item.min)
            }else {
                value.push([item.min, item.max])
            }

            screening_conditions.push(value)
        }



        if(!success) return


        if(industry.value && industry.value.length > 0) {
            code = industry.value[industry.value.length - 1]
        }

        dataSource.splice(0)
        loading.value = true
        const res = await stockSelectorApi({code, screening_conditions : JSON.stringify(screening_conditions)})
        loading.value = false
        if(res.success) {
            if(res.data) {
                dataSource.push(...res.data)
            }
        }else {
            message.error(res.message)
        }

    }

    defineExpose({
        selectedRows
    })

</script>


<style module lang='scss'>
    .hidden{
        display: none;
    }
    .industry{
        display: flex;
        align-items: center;
    }

    .zhibiao{
        display: flex;
        //align-items: center;

        
    }

    .zhibiaoTable{
        :global(.ant-descriptions-item-content){
            vertical-align: top !important;
        }
    }

    .table{
        border-collapse: separate;
        border-spacing: 0;
        text-align: center;
        

        th{
            height: 46px;
            font-weight: normal;
            border-bottom: 1px solid $border-color;
        }

        td{
            padding: 10px 0;
        }
    }
    
    .between{
        margin: 0 10px;
        font-size: 12px;
    }

    .percentSign{
        //font-size: 12px;
        color: #999;
        margin-left: 3px;
    }

    .valueInput{
        width: 60px;
    }

    .error{
        color: red;
        position: absolute;
        left: 50%;
        top: 100%;
        transform: translate(-50%, 3px);
    }

    .resultTable{
        :global(.ant-table-cell){
            text-align: center;
        }
    }

    .title{
        font-size: 14px;
        font-weight: bold;
    }
    
</style>